package router

import (
	"InstantCommunication/docs"
	"InstantCommunication/service"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/validator/v10"
	swaggerFiles "github.com/swaggo/files"
	ginSwagger "github.com/swaggo/gin-swagger"
	"regexp"
)

func validPhone(fl validator.FieldLevel) bool {
	if s, ok := fl.Field().Interface().(string); ok {
		regRuler := "^1[345789]{1}\\d{9}$"
		reg := regexp.MustCompile(regRuler)
		return reg.MatchString(s)
	}
	return true
}

func Router() *gin.Engine {
	// 静态资源
	r := gin.Default()
	r.Static("/asset", "asset/")
	r.LoadHTMLGlob("views/**/*")

	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		_ = v.RegisterValidation("validPhone", validPhone)
	}
	// swagger相关
	docs.SwaggerInfo.BasePath = ""
	r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

	// 首页
	r.GET("/", service.GetIndex)
	r.GET("/index", service.GetIndex)
	r.GET("/toRegister", service.ToRegister)
	r.GET("/toChat", service.ToChat)

	r.POST("/searchFriends", service.SearchFriends)

	// 用户相关
	r.GET("/user/getUserList", service.GetUserList)
	r.POST("/user/createUser", service.CreateUser)
	r.GET("/user/deleteUser", service.DeleteUser)
	r.POST("/user/updateUser", service.UpdateUser)
	r.POST("/user/findUserByNameAndPassword", service.FindUserByNameAndPassword)

	r.GET("/user/sendMessage", service.SendMessage)
	r.GET("/user/SendUserMessage", service.SendUserMessage)
	return r
}
